<!--  -->
<template>
    <div class="main_container">
        <div class="custform_nav">
            <div>
                <div class="im-export">
                    <el-button type="success" @click="triggerFileInput">重新导入</el-button>
                    <input type="file" ref="fileInput" v-show="false" @change="importData" accept=".xlsx, .xls, .csv" />
                    <div>
                        <el-button type="primary" @click="exportData">导出信息</el-button>   
                    </div>                 
                </div>
                <el-input v-model="search_data.staff_id" size="medium" placeholder="请输入ID搜索" style="width: 200px;"/>
                <el-button type="primary" @click="search">搜索</el-button>
                <el-button type="success" @click="add">添加</el-button>
                <!-- 添加用户弹窗 -->
                <el-dialog v-model="dialogVisible"  width="25%">
                    <div class="add_title">
                        <p>添加员工信息</p>
                    </div>
                    <el-form ref="userForm" :model="add_data" label-width="100px">
                        <el-form-item label="姓名">
                            <el-input v-model="add_data.staff_name" placeholder="请输入员工姓名"></el-input>
                        </el-form-item>
                        <el-form-item label="部门">
                            <el-select v-model="add_data.department_id" placeholder="请选择部门">
                                <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label     "
                                    :value="item.value">
                                </el-option>
                            </el-select>                            
                        </el-form-item>
                        <el-form-item label="性别">
                            <el-radio v-model="add_data.sex" label="男">男</el-radio>
                            <el-radio v-model="add_data.sex" label="女">女</el-radio>                    
                        </el-form-item>
                        <el-form-item label="地址">
                            <el-input v-model="add_data.address" placeholder="请输入地址"></el-input>
                        </el-form-item>
                        <el-form-item label="联系方式">
                            <el-input v-model="add_data.mobile" placeholder="请输入联系方式"></el-input>
                        </el-form-item>
                    </el-form>
                    <div class="add_btn">
                        <el-button @click="closeadd">取消</el-button>
                        <el-button type="primary" @click="submitForm">确定</el-button>
                    </div>
                </el-dialog>
            </div>
        </div>
        <el-table :data="staff_tabledata" style="width: 100%">
            <el-table-column label="ID" prop="staff_id" />
            <el-table-column label="姓名" prop="staff_name" />
            <el-table-column label="部门" prop="department_id" :formatter="formatDepartmentName"/>
            <el-table-column label="业绩" prop="performance" />
            <el-table-column label="性别" prop="sex" />
            <el-table-column label="联系方式" prop="mobile" />
            <el-table-column label="地址" prop="address" />
            <el-table-column label="创建时间" prop="created_time">
                <template #default="scope">
                    {{ formatDate(scope.row.created_time) }}
                </template>
            </el-table-column>
            <el-table-column label="更新时间" prop="updated_time">
                <template #default="scope">
                    {{ formatDate(scope.row.updated_time) }}
                </template>
            </el-table-column>
            <el-table-column align="right">
                <template #default="scope">
                    <el-button-group>
                        <el-button type="warning" size="small" @click="update(scope.row)">
                            修改
                        </el-button>                   
                        <el-button
                            size="small"
                            type="danger"
                            @click="del(scope.row.staff_id)"
                        >
                            删除
                        </el-button>
                    </el-button-group>                
                </template>
            </el-table-column>
        </el-table>
        <el-dialog v-model="dialogVisible_update"  width="25%">
            <div class="add_title">
                <p>修改员工信息</p>
            </div>
            <el-form ref="updateForm" :model="update_data" label-width="100px">
                <el-form-item label="姓名">
                    <el-input v-model="update_data.staff_name" placeholder="请输入员工姓名"></el-input>
                </el-form-item>
                    <el-form-item label="部门">
                        <el-select v-model="update_data.department_id" placeholder="请选择部门">
                            <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label     "
                                :value="item.value">
                            </el-option>
                        </el-select>                            
                    </el-form-item>
                <el-form-item label="性别">
                    <el-radio v-model="update_data.sex" label="男">男</el-radio>
                    <el-radio v-model="update_data.sex" label="女">女</el-radio>                    
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="update_data.address" placeholder="请输入地址"></el-input>
                </el-form-item>
                <el-form-item label="联系方式">
                    <el-input v-model="update_data.mobile" placeholder="请输入联系方式"></el-input>
                </el-form-item>
            </el-form>
            <div class="add_btn">
                <el-button @click="closeupdate">取消</el-button>
                <el-button type="primary" @click="submitForm_update">确定</el-button>
            </div>
        </el-dialog>         
    </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';
import * as XLSX from 'xlsx';

const now = new Date().toISOString(); // 实时时间戳

const api = {
    searchurl: "/api/staff/search", 
    loadurl: "/api/login/list",
    addurl: "/api/staff/add",
    updateurl: "/api/staff/update",   
    deleteurl: "/api/staff/delete",
    importurl: "/api/staff/import"        
};

const search_data = ref({
    staff_id: ''
});

// 时间格式切换
function formatDate(isoString) {
    const date = new Date(isoString);
    const utcDate = new Date(date.toISOString()); // 确保输入是 UTC 时间
    utcDate.setUTCHours(utcDate.getUTCHours() - 8); // 转换为东八区时间

    const year = utcDate.getFullYear();
    const month = String(utcDate.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
    const day = String(utcDate.getDate()).padStart(2, '0');
    const hours = String(utcDate.getHours()).padStart(2, '0');
    const minutes = String(utcDate.getMinutes()).padStart(2, '0');
    const seconds = String(utcDate.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const staff_tabledata = ref([]);

// *客户信息导出功能
const exportData = () => {
    // 创建一个工作簿
    const wb = XLSX.utils.book_new();

    // 将数据转换为工作表
    const ws = XLSX.utils.json_to_sheet(staff_tabledata.value);

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, 'Staff');

    // 导出文件
    XLSX.writeFile(wb, 'staff.xlsx');
    ElMessage.success('导出成功');
};

//*客户信息导入
const importData = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    try {
        // 使用 FileReader 读取文件内容
        const reader = new FileReader();
        reader.onload = (e) => {
            const data = e.target.result;
            const workbook = XLSX.read(data, { type: 'binary' });
            const sheetName = workbook.SheetNames[0]; // 获取第一个
            const worksheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet); // 将工作表转换为 JSON 格式

            // 转换为后端期望的格式
            const staff = jsonData.map((row) => ({
                staff_id: row['staff_id'], 
                staff_name: row['staff_name'], 
                department_id: row['department_id'],
                performance: row['performance'],
                username: row['username'],
                password: row['password'],
                sex: row['sex'],
                mobile: row['mobile'],                 
                address: row['address'], 
                created_time: new Date().toISOString(), 
                updated_time: new Date().toISOString() 
            }));

            // 发送 JSON 数据到后端
            axios.put(api.importurl, staff, {
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                ElMessage.success('导入成功');
                console.log(response.data);
                loaddate(); // 刷新数据
            })
            .catch(error => {
                ElMessage.error('导入失败：' + error.message);
                console.error(error);
            });
        };
        reader.readAsBinaryString(file); // 读取文件内容
    } catch (error) {
        ElMessage.error('导入失败：' + error.message);
        console.error(error);
    }
};

const triggerFileInput = () => {
    const fileInput = document.querySelector('input[type="file"]');
    if (fileInput) {
        fileInput.click();
    }
};

// *搜索
const search = async () => {
    if (!search_data.value.staff_id){ 
        loaddate(); 
        return;
    }
    try {
        let result = await axios.post(api.searchurl, {
            staff_id: search_data.value.staff_id
        });       
        if(result.data){
            staff_tabledata.value = [result.data];     
            ElMessage.success('查询成功');
        }else{
            ElMessage.error('未匹配到相关查询');
        }
    } catch (error) {
        ElMessage.error('搜索失败:输入了非法字符或者长度不符');
        console.error(error);
    }
};

//*添加

const dialogVisible = ref(false); // 控制弹窗的显示与隐藏

const add_data = ref({
    staff_id: null,
    staff_name: '', 
    department_id: null,
    performance: '',
    username: null,
    password: null, 
    sex: '',
    mobile: '',
    address: '',
    created_time: now,
    updated_time: now
});

const add = () => {
  dialogVisible.value = true;
};
const value = ref();

const options = ref([
    { value: 1001, label: "销售部" },
    { value: 1002, label: "市场部" },
    { value: 1003, label: "技术部" },
    { value: 1004, label: "人力资源部" },
    { value: 1005, label: "财务部" },
    { value: 1006, label: "客服部" },
    { value: 1007, label: "采购部" },
    { value: 1008, label: "研发部" },
    { value: 1009, label: "行政部" },
    { value: 1010, label: "物流部" }
]);


// 根据部门 ID 获取部门名称
const formatDepartmentName = (row, column, cellValue) => {
    const department = options.value.find(option => option.value === cellValue);
    return department ? department.label : '未知部门';
};

const closeadd = () => {
  add_data.value = {
    staff_id: null,
    staff_name: '', 
    department_id: null,
    performance: '',
    username: null,
    password: null, 
    sex: '',
    mobile: '',
    address: '',
    created_time: now,
    updated_time: now
  };
  dialogVisible.value = false;
};

// 提交表单
const submitForm = async () => {
    try {
        const response = await axios.post(api.addurl, add_data.value);
        ElMessage.success('用户添加成功');
        console.log(response.data);
        closeadd();
        loaddate(); // 刷新数据
    } catch (error) {
        ElMessage.error('添加失败：' + error.message);
        console.error(error);
    }
};

// *修改
const dialogVisible_update = ref(false); // 控制弹窗的显示与隐藏

const update_data = ref({
    staff_id: null,
    staff_name: '',
    department_id: null,
    performance: '',
    username: null,
    password: null, 
    sex: '',
    mobile: '',
    address: '',
    created_time: null,
    updated_time: now
});

const update = (row) => {
    update_data.value.staff_id = row.staff_id;
    update_data.value.staff_name = row.staff_name;
    update_data.value.department_id = row.department_id;
    console.log(row.department_id);
    update_data.value.performance = row.performance;
    update_data.value.username = row.username; 
    update_data.value.password = row.password; 
    update_data.value.sex = row.sex;
    update_data.value.mobile = row.mobile;    
    update_data.value.address = row.address;
    update_data.value.created_time = row.created_time;
    update_data.value.updated_time = row.updated_time;
    nextTick(() => {
        dialogVisible_update.value = true;
    });
};

const closeupdate = () => {
  update_data.value = {
    staff_id: null,
    staff_name: '', 
    department_id: null,
    performance: '',
    username: null,
    password: null, 
    sex: '',
    mobile: '',
    address: '',
    created_time: null,
    updated_time: now
  };
  dialogVisible_update.value = false;
};

const submitForm_update = async () => {
    try {
        const response = await axios.put(`${api.updateurl}/${update_data.value.staff_id}`, update_data.value);
        ElMessage.success('用户更新成功');
        console.log(response.data);
        closeupdate();
        loaddate(); // 刷新数据
    } catch (error) {
        ElMessage.error('更新失败：' + error.message);
        console.error(error);
    }
};

// *删除
const del = async (staffId) => {
    try {
        const confirmDelete = confirm("确定要删除该用户吗？");
        if (!confirmDelete) {
            return;
        }
        let result = await axios.delete(api.deleteurl + `/${staffId}`);
        ElMessage.success('删除成功');
        loaddate();
    } catch (error) {
        ElMessage.error('删除失败：' + error.message);
        console.error(error);
    }
};

// 刷新页面

// *加载
const loaddate = async () => {
    try {
        let result = await axios.get(api.loadurl);
        staff_tabledata.value = result.data; 
    } catch (error) {
        ElMessage.error('加载数据失败：' + error.message);
        console.error(error);
    }
};
  
loaddate();

</script>

<style scoped>

    .add_title{
        padding-bottom:20px;
    }
    .add_title>p{
        text-align: center;
        font-size: 20px;
    }

    .add_btn{
        padding: 10px;
        text-align: center;
    }

    .common-layout>ul {
        height: 80px;
    }
    .el-menu el-menu--horizontal el-menu-demo{
        min-width: 1588px;
    }
    .main_container{
        min-width: 80% ;

    }
    .custform_nav{
        margin: 20px;
    }
    .custform_nav>div{
        min-width: 380px;
        display: flex;

    }
    .im-export{
        display: flex;
        width: 200px;
        padding-right: 72%;
    }
    .im-export>button{
        margin-right:20px;
    }

</style>
